<?php
use Inationsoft\NS;
use Inationsoft\NS\Core\Controller;
use Inationsoft\NS\Core\Model;
use Inationsoft\NS\Core\Config;
use Inationsoft\NS\IO\Directory;
use Inationsoft\NS\Net\Http\Cookie;
use Inationsoft\NS\String;
use Inationsoft\NS\UI\ScriptManager;
use Inationsoft\NS\UI\StyleManager;
use Inationsoft\Koma;
use Inationsoft\Koma\User;

define('DEFAULT_PAGE_LIMIT', 15);

class Application extends Controller {
	private $_model, $_redirectBase;

	function _main() {
		$this->_model = Model::getInstance('ApplicationModel');
		$this->_redirectBase = 'system/' . String::toLowerCase(get_class($this));

		$js = ScriptManager::getInstance();
		$js->addSource(NS_JQUERY_PATH);
		$js->addSource(NS_JQUERY_UI_PATH);
		$js->addSource($this->Path . '/assets/js/application.js');
		StyleManager::getInstance()->addSource(NS_JQUERY_UI_STYLE_PATH);

		$this->View->assign('app_base_url', NS_BASE_URL . '/' . $this->_redirectBase);
	}

	function index($page_limit = DEFAULT_PAGE_LIMIT, $page = 1) {
		$apps_path = NS_SYSTEM_PATH . '/' . current(explode('/', Config::getInstance()->ApplicationFolder));
		$dir = new Directory($apps_path);
		$files = $dir->toArray();

		$apps = array();

		foreach($files as $item) {
			if($item == '.' || $item == '..') continue;

			if(is_readable($apps_path . '/'. $item . '/info.php')) {
				include($apps_path . '/'. $item . '/info.php');

				$Application['Path'] = $item;
				$apps[md5($Application['Name'])] = $Application;
			}
		}

		//$condition = null;
		//$search_keyword = null;
		//$search_column = null;
		//$cookie = Cookie::getInstance();

		/*
		if($this->Request->Post->value('token')) {
			$search_keyword = $this->Request->Post->value('search_keyword') ? $this->Request->Post->value('search_keyword') : null;
			$search_column = $this->Request->Post->value('search_column');
			$page_limit = $this->Request->Post->value('page_limit');
		} else {
			if($cookie->get('search_token') === md5($cookie->get('search_keyword') . get_class($this) . User::getInstance()->Token)) {
				$search_keyword = $cookie->get('search_keyword');
				$search_column = $cookie->get('search_column');
			}
		}
		*/

		/*
		if(!empty($search_keyword)) {
			$condition = $this->_model->createFilterCriteria();
			$condition->contains($search_column, $search_keyword);

			$cookie->set('search_keyword', $search_keyword);
			$cookie->set('search_column', $search_column);
			$cookie->set('search_token', md5($search_keyword . get_class($this) . User::getInstance()->Token));
		} else {
			$cookie->delete('search_keyword');
			$cookie->delete('search_column');
			$cookie->delete('search_token');
		}

		$cookie->set('page', $page);
		$cookie->set('page_limit', $page_limit);
		*/
		
		foreach($this->_model->getAll() as $item) {
			if(isset($apps[md5($item['application_name'])])) {
				$apps[md5($item['application_name'])]['Installed'] = $item;
			}
		}

		$this->View->File = 'application/index.php';
		$this->View->assign(array(
			//'token' => md5(User::getInstance()->Token . get_class($this)),
			'datas' => $apps,
			'data_count' => count($apps),
			//'page' => $page,
			//'page_limit' => $page_limit,
			//'search_keyword' => $search_keyword
		));
	}

	function delete($ids) {
		if($this->Request->Post->value('token') != md5(User::getInstance()->Token . get_class($this) )) $this->redirect($this->_redirectBase . '/index');

		$this->_model->deleteSelected($this->Request->Post->value($this->_model->PrimaryKey));
		$this->redirect($this->_redirectBase . '/index');
	}

	function install($app) {
		$apps_path = NS_SYSTEM_PATH . '/' . current(explode('/', Config::getInstance()->ApplicationFolder));

		if(is_readable($apps_path . '/'. $app . '/info.php')) {
			include($apps_path . '/'. $app . '/info.php');
			$datas['application_name'] = $Application['Name'];
			$datas['application_path'] = $app;
			$datas['install_token'] = md5(time() . $app . Config::getInstance()->Application->Salt);
			$datas['installed_time'] = time();
			$datas['updated_time'] = $datas['installed_time'];
			$datas['is_enabled'] = 1;

			if($app_id = $this->_model->saveData($datas, false)) {
				foreach($Application['Blocks'] as $path => $block) {
					$block_datas['application_id'] = $app_id;
					$block_datas['block_path'] =  $path;
					$block_datas['is_enabled'] = 1;

					$this->_model->saveBlock($block_datas);
				}

				$this->redirect($this->_redirectBase . '/index');
			}
		}

		$this->redirect($this->_redirectBase . '/index', 'Failed when installing application...');
	}

	function uninstall($app, $install_id, $install_token) {
		$apps_path = NS_SYSTEM_PATH . '/' . current(explode('/', Config::getInstance()->ApplicationFolder));

		if(!empty($install_token) && is_readable($apps_path . '/'. $app . '/info.php')) {
			$this->_model->delete(array('application_id' => $install_id, 'install_token' => $install_token), array('koma_blocks'));
		}

		$this->redirect($this->_redirectBase . '/index');
	}
	
	function status($install_id, $status) {
		$datas['application_id'] = $install_id;
		$datas['updated_time'] = time();
		$datas['is_enabled'] = $status;

		if($this->_model->saveData($datas, true)) {
			$this->redirect($this->_redirectBase . '/index');
		}

		$this->redirect($this->_redirectBase . '/index');
	}

	function detail($id, $print = false) {
		if(!$datas = $this->_model->get($id)) {
			$this->redirect($this->_redirectBase . '/index');
		}

		if($print) {
			$this->Render = false;
			$this->View->File = 'application/print.php';
		} else {
			$this->View->File = 'application/detail.php';
		}

		$this->form($datas, true);
	}

	function save() {
		if($this->Request->Post->value('dispatch') != 'save') $this->redirect($this->_redirectBase . '/index');
		if($this->Request->Post->value('token') != md5(User::getInstance()->Token . get_class($this) )) $this->redirect($this->_redirectBase . '/index');
		if($this->Request->Post->value('edit_token') && $this->Request->Post->value('edit_token') != md5(User::getInstance()->Token . $this->Request->Post->value($this->_model->PrimaryKey) . get_class($this))) $this->redirect($this->_redirectBase . '/index');

		$is_edit = ($this->Request->Post->value('edit_token') ? true : false);
		$cookie = Cookie::getInstance();

		if($this->_model->saveData($this->Request->Post->value(), $is_edit)) {
			$page = (!$is_edit ? ceil($this->_model->count() / ($cookie->get('page_limit') ? $cookie->get('page_limit') : DEFAULT_PAGE_LIMIT)) : (Cookie::getInstance()->get('page') ? Cookie::getInstance()->get('page') : 1));
			$page_limit =  ($cookie->get('page_limit') ? $cookie->get('page_limit') : DEFAULT_PAGE_LIMIT);
			$this->redirect($this->_redirectBase . '/index/' . $page_limit . '/' . $page, 'Success saving data...');
		}
		else $this->redirect($this->_redirectBase . '/index', 'Failed when saving data...');
	}

	private function form($datas, $is_edit = false) {
		$this->View->assign('token', md5(User::getInstance()->Token . get_class($this)));
		$this->View->assign('datas', $datas);
	}
}
?>